"""
大模型调用优化配置
用于配置缓存、合并策略等优化参数
"""

class OptimizationConfig:
    """优化配置类"""
    
    # 缓存配置
    CACHE_TTL = 3600  # 缓存有效期（秒），默认1小时
    ENABLE_CACHE = True  # 是否启用缓存
    
    # 智能合并策略配置
    ENABLE_SMART_MERGE = True  # 是否启用智能合并
    MAX_MODULES_FOR_MERGE = 5  # 启用合并的最大模块数
    MAX_CONTENT_LENGTH_FOR_MERGE = 2000  # 启用合并的最大内容长度
    MAX_MODULES_PER_GROUP = 3  # 每组最大模块数
    MODULE_SIMILARITY_THRESHOLD = 0.3  # 模块相似度阈值
    
    # 策略选择阈值
    SIMPLE_STRATEGY_MAX_MODULES = 3  # 简单策略最大模块数
    SIMPLE_STRATEGY_MAX_CONTENT = 2000  # 简单策略最大内容长度
    COMPLEX_STRATEGY_MIN_MODULES = 5  # 复杂策略最小模块数
    COMPLEX_STRATEGY_MIN_CONTENT = 5000  # 复杂策略最小内容长度
    
    # 重试优化配置
    ENABLE_SMART_RETRY = True  # 是否启用智能重试
    MAX_RETRIES = 3  # 最大重试次数
    RETRY_DELAY_BASE = 2.0  # 重试延迟基数（秒）
    
    # 性能监控配置
    ENABLE_PERFORMANCE_LOGGING = True  # 是否启用性能日志
    LOG_API_CALLS = True  # 是否记录API调用
    LOG_CACHE_HITS = True  # 是否记录缓存命中
    
    @classmethod
    def get_cache_config(cls):
        """获取缓存配置"""
        return {
            'ttl': cls.CACHE_TTL,
            'enabled': cls.ENABLE_CACHE
        }
    
    @classmethod
    def get_merge_config(cls):
        """获取合并策略配置"""
        return {
            'enabled': cls.ENABLE_SMART_MERGE,
            'max_modules': cls.MAX_MODULES_FOR_MERGE,
            'max_content_length': cls.MAX_CONTENT_LENGTH_FOR_MERGE,
            'max_modules_per_group': cls.MAX_MODULES_PER_GROUP,
            'similarity_threshold': cls.MODULE_SIMILARITY_THRESHOLD
        }
    
    @classmethod
    def get_strategy_config(cls):
        """获取策略选择配置"""
        return {
            'simple': {
                'max_modules': cls.SIMPLE_STRATEGY_MAX_MODULES,
                'max_content': cls.SIMPLE_STRATEGY_MAX_CONTENT
            },
            'complex': {
                'min_modules': cls.COMPLEX_STRATEGY_MIN_MODULES,
                'min_content': cls.COMPLEX_STRATEGY_MIN_CONTENT
            }
        }
    
    @classmethod
    def should_use_cache(cls):
        """是否应该使用缓存"""
        return cls.ENABLE_CACHE
    
    @classmethod
    def should_use_smart_merge(cls, modules_count: int, content_length: int):
        """是否应该使用智能合并"""
        if not cls.ENABLE_SMART_MERGE:
            return False
        
        return (modules_count <= cls.MAX_MODULES_FOR_MERGE and 
                content_length <= cls.MAX_CONTENT_LENGTH_FOR_MERGE)
    
    @classmethod
    def get_strategy_for_modules(cls, modules_count: int, content_length: int):
        """根据模块数量和内容长度选择策略"""
        if modules_count <= cls.SIMPLE_STRATEGY_MAX_MODULES and content_length <= cls.SIMPLE_STRATEGY_MAX_CONTENT:
            return "simple"
        elif modules_count >= cls.COMPLEX_STRATEGY_MIN_MODULES or content_length >= cls.COMPLEX_STRATEGY_MIN_CONTENT:
            return "complex"
        else:
            return "smart_merge"


# 性能统计类
class PerformanceStats:
    """性能统计"""
    
    def __init__(self):
        self.reset()
    
    def reset(self):
        """重置统计"""
        self.total_requests = 0
        self.cache_hits = 0
        self.api_calls = 0
        self.total_time = 0.0
        self.strategy_usage = {
            'simple': 0,
            'smart_merge': 0,
            'complex': 0
        }
    
    def record_request(self, duration: float, strategy: str, cache_hit: bool = False, api_calls: int = 1):
        """记录请求"""
        self.total_requests += 1
        self.total_time += duration
        
        if cache_hit:
            self.cache_hits += 1
        else:
            self.api_calls += api_calls
        
        if strategy in self.strategy_usage:
            self.strategy_usage[strategy] += 1
    
    def get_stats(self):
        """获取统计信息"""
        cache_hit_rate = (self.cache_hits / self.total_requests * 100) if self.total_requests > 0 else 0
        avg_time = (self.total_time / self.total_requests) if self.total_requests > 0 else 0
        avg_api_calls = (self.api_calls / (self.total_requests - self.cache_hits)) if (self.total_requests - self.cache_hits) > 0 else 0
        
        return {
            'total_requests': self.total_requests,
            'cache_hits': self.cache_hits,
            'cache_hit_rate': f"{cache_hit_rate:.1f}%",
            'total_api_calls': self.api_calls,
            'avg_api_calls_per_request': f"{avg_api_calls:.1f}",
            'total_time': f"{self.total_time:.2f}s",
            'avg_time_per_request': f"{avg_time:.2f}s",
            'strategy_usage': self.strategy_usage
        }


# 全局性能统计实例
performance_stats = PerformanceStats()


def get_optimization_summary():
    """获取优化效果总结"""
    stats = performance_stats.get_stats()
    
    return {
        'optimization_enabled': {
            'cache': OptimizationConfig.ENABLE_CACHE,
            'smart_merge': OptimizationConfig.ENABLE_SMART_MERGE,
            'smart_retry': OptimizationConfig.ENABLE_SMART_RETRY
        },
        'performance_stats': stats,
        'estimated_savings': {
            'api_calls_saved': f"{stats['cache_hits']}次",
            'time_saved_by_cache': f"约{stats['cache_hits'] * 10}秒",
            'cost_reduction': f"约{(stats['cache_hits'] / max(stats['total_requests'], 1)) * 100:.1f}%"
        }
    }
